package com.xcm.core.interceptor;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xcm.constant.ClientConstant;
import com.xcm.core.annotation.ClientPermissionRequired;

@Component
public class ClientPermissionInterceptor implements HandlerInterceptor{
	private static Logger logger = LoggerFactory.getLogger(ClientPermissionInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.info("###@request URI "  + request.getRequestURL());
		logger.info("###@request params "  + JSON.toJSONString(request.getParameterMap()));
		logger.info("###@request headers : " + JSON.toJSONString(getHeadersInfo(request)));
		if ( hasPermission(handler) ) {
			return true;
		}
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			ObjectMapper json = new ObjectMapper();
			map.put(ClientConstant.CODE, ClientConstant.CODE_PERMISSION_DENIED);
			map.put(ClientConstant.MSG, ClientConstant.MSG_PERMISSION_DENIED);
			response.setContentType("text/javascript;charset=utf-8");
			response.getWriter().write(json.writeValueAsString(map));
			//response.sendError(HttpStatus.FORBIDDEN.value(), "访问被限制");
		} catch (IOException e1) {
			logger.error(e1.getMessage(), e1);
		}
        return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
	
	/**
     * 客户端是否有访问权限
     * @param handler
     * @return
     */
    private boolean hasPermission(Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            ClientPermissionRequired clientPermissionRequired = handlerMethod.getMethod().getAnnotation(ClientPermissionRequired.class);
            // 如果方法上的注解为空 则获取类的注解
            if (clientPermissionRequired == null) {
            	clientPermissionRequired = handlerMethod.getMethod().getDeclaringClass().getAnnotation(ClientPermissionRequired.class);
            }
            // 如果标记了注解，则判断权限
            if (clientPermissionRequired != null) {
            	logger.info("============clientPermissionInterceptor invoke!!!");
                // TODO check client is right access here.
            	return true;
            }
        }
        return true;
    }
    
    private Map<String, String> getHeadersInfo(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
      }
}
